package com.tc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tc.domain.Sys_user;
import com.tc.dto.UserDTO;
import com.tc.dto.UserQueryDTO;
import com.tc.service.ISys_userService;
import com.tc.utils.JWT;
import com.tc.utils.ResultVo;
import com.tc.vo.UserInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 用户信息前端控制器
 * </p>
 *
 * @author tc
 * @since 2025-07-10
 */
@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户管理")
public class Sys_userController {

    @Autowired
    private ISys_userService userService;

    @GetMapping("/info")
    @ApiOperation("获取当前用户信息")
    public ResultVo<UserInfoVO> getCurrentUserInfo(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        if (token == null) {
            return ResultVo.error(401, "未授权访问");
        }

        String userIdStr = JWT.getUserIdFromToken(token);
        if (userIdStr == null) {
            return ResultVo.error(401, "令牌无效");
        }

        Long userId = Long.valueOf(userIdStr);
        UserInfoVO userInfo = userService.getUserInfo(userId);

        if (userInfo == null) {
            return ResultVo.error(404, "用户不存在");
        }

        return ResultVo.ok(userInfo);
    }

    @PostMapping("/page")
    @ApiOperation("分页查询用户信息")
    public ResultVo<?> getUserPage(@RequestBody UserQueryDTO userDTO) {
        Page<Sys_user> page = new Page<>(userDTO.getCurrent(), 3);
        QueryWrapper<Sys_user> qw = new QueryWrapper<>();
        qw.eq("deleted", 0); // 显示
        userService.page(page, qw);
        return ResultVo.ok(page);
    }

    @PostMapping("/update")
    @ApiOperation("更新用户信息")
    public ResultVo<Boolean> updateUserInfo(@RequestBody UserDTO userDTO) {
        try {

            // 这里可以添加一些验证逻辑，比如检查用户是否存在等
            if( userDTO.getUserId() == null) {
                return ResultVo.fail("用户ID不能为空");
            }
            // 简单的更新操作，直接使用MyBatis-Plus
            Sys_user user = new Sys_user();
            BeanUtils.copyProperties(userDTO, user);

            boolean result = userService.updateById(user);
            if (result) {
                return ResultVo.ok(true, "修改信息成功");
            } else {
                return ResultVo.fail("修改信息失败");
            }
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/add")
    @ApiOperation("添加新用户")
    public ResultVo<Boolean> addUser(@RequestBody  UserDTO userDTO) {
        try {
            // 这里可以添加一些验证逻辑，比如检查用户是否已存在等
            if (userDTO.getUsername() == null || userDTO.getPassword() == null) {
                return ResultVo.fail("用户名和密码不能为空");
            }
            // 检查用户名是否已存在
            QueryWrapper<Sys_user> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", userDTO.getUsername());
            Sys_user existingUser = userService.getOne(queryWrapper);
            if (existingUser != null) {
                return ResultVo.fail("用户名已存在");
            }
            // 简单的更新操作，直接使用MyBatis-Plus
            Sys_user user = new Sys_user();
            BeanUtils.copyProperties(userDTO, user);

            boolean result = userService.save(user);
            if (result) {
                return ResultVo.ok(true, "新增用户信息成功");
            } else {
                return ResultVo.fail("新增用户信息失败");
            }
        } catch (Exception e) {
            return ResultVo.error(e);
        }
    }

    @PostMapping("/delete")
    @ApiOperation("删除用户")
    public ResultVo<Boolean> deleteUser(@RequestParam Long userId) {


        try {

            // 检查用户ID是否有效
            if (userId == null) {
                return ResultVo.fail("用户ID不能为空");
            }
            boolean result = userService.removeById(userId);
            if (result) {
                return ResultVo.ok(true, "删除用户成功");
            } else {
                return ResultVo.fail("删除用户失败");
            }
        } catch (Exception e) {
            return ResultVo.error(e);
        }
    }


    /**
     * 从请求中获取令牌
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}

